<?php
/*
 * @FilePath: \crm\application\crm\controller\BaseController.php
 */

namespace app\crm\controller;

use app\crm\model\auth\AuthNode;
use app\crm\model\auth\Role;
use think\captcha\Captcha;
use think\Controller;
use think\facade\Request;


class BaseController extends Controller
{
    protected function initialize()
    {
        $this->checkAuth();
    }

    private function checkAuth()
    {
        $admin = session('admin');
        $expireTime = session('admin.expire_time');

        // 验证登录
        if (empty($admin)) {
            $this->error('请先登录后台', '/crm/login/index');
        } else {
            // 验证是否登录过期 , 没过期更新session
            if (time() > $expireTime) {
                session('admin', null);
                $this->error('登录已过期,请重新登录', '/crm/login/index');
            } else {
                session('admin.expire_time', time() + 7200);
            }
        }

        // 验证权限
        $url = '/' . Request::module() . '/' . Request::controller() . '/' . Request::action();
        $id = AuthNode::where('node', $url)->field('id')->find();
        $NodeList = explode(',', Role::where('id', $admin['role_id'])->find()['node_id']);

        if (!empty($id)) {
            if (array_search($id['id'], $NodeList) == false) {
                $this->error('无权限访问');
            }
        }
    }
}
